const fs = require('fs');
const path = require('path');

const directory = require('./directory');




/**
 * 初始化平台
 * 
 * @param {String} platform 平台名 h5 || wx || web 必填
 * @param {String} projectsDirectoryPath projects目录绝对路径 平台标准为"projects"指向的目录 必填
 */
module.exports = function (platform, projectsDirectoryPath) {

    if (!platform)
    {
        throw new Error('call method yaxi.webpack.platform error, publish.platform property can not be empty!');
    }

    if ('h5|wx|web'.split('|').indexOf(platform) < 0)
    {
        throw new Error('call method yaxi.webpack.platform error, publish.platform only supports h5 or wx or web!');
    }

    if (!projectsDirectoryPath)
    {
        throw new Error('call method yaxi.webpack.platform error, publish.projectsDirectoryPath property can not be empty!');
    }

    if (!projectsDirectoryPath.endsWith(platform))
    {
        projectsDirectoryPath = path.join(projectsDirectoryPath, platform);
    }


    // 平台模板路径
    let templatePath = path.join(__dirname, '../platforms', platform);

    // 平台目录已存在则执行清理
    if (fs.existsSync(projectsDirectoryPath))
    {
        // 清除yaxi库
        directory.clean(path.join(projectsDirectoryPath, 'yaxi'));
    }
    else // 创建平台目录
    {
        directory.make(projectsDirectoryPath);
    }

    // 复制yaxi库到开发目录的对应平台下
    let names = fs.readdirSync(templatePath);

    for (let i = 0, l = names.length; i < l; i++)
    {
        let name = names[i];
        let source = path.join(templatePath, name);
        let target = path.join(projectsDirectoryPath, name);

        if (fs.statSync(source).isFile())
        {
            // 第一层的文件已经存在则不覆盖
            if (!fs.existsSync(target))
            {
                fs.copyFileSync(source, target);
            }
        }
        else // 其它目录直接覆盖
        {
            directory.copy(source, target);
        }
    }
}
